#ifndef CREPLICATOR_H
#define CREPLICATOR_H

#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QObject>
#include <QStringList>

#include <QtDebug>

#include "src/cdatabase.h"

class CReplicator : public QObject
{
    Q_OBJECT
public:
    CReplicator(CDatabase*);

    QNetworkReply *post(const QString = "https://passworder.ru/work.php");

    void addField(QString name, QString value);
    void addFile(QString fieldName, QByteArray file, QString name);
    void synchronize();
    void setLogin(QString str) { addField("login", str); }
    void setPassword(QString str) { addField("password", str); }

    QString replyPhrase() { return m_replyPhrase; }
    QByteArray& replyData() { return m_replyData; }

public slots:
    void abort() { m_reply->abort(); }

private:
    QNetworkAccessManager *m_manager;
    CDatabase *m_db;

    QStringList m_fieldNames;
    QStringList m_fieldValues;
    QStringList m_fileFieldNames;
    QStringList m_fileNames;
    QList<QByteArray> m_files;

    QByteArray m_replyData;
    int m_replyCode;
    QString m_replyPhrase;

    QNetworkReply *m_reply;

    void debug(QString msg) const { qDebug() << "[Replicator]\t" + msg; }

private slots:
    void sslerr(QNetworkReply* reply, const QList<QSslError>& errors);
    void readData(QNetworkReply* reply);

signals:
    void downloadProgress(qint64 bytesReceived, qint64 bytesTotal);
    void error(QNetworkReply::NetworkError code);
    void uploadProgress(qint64 bytesSent, qint64 bytesTotal);
    void received(int);
};

#endif // CREPLICATOR_H

